import os

from google.appengine.ext import webapp
from google.appengine.ext.webapp.util import run_wsgi_app
from google.appengine.ext.webapp import template

class GetPackages(webapp.RequestHandler):
    def get(self):
        
        self.response.headers['Content-Type'] = 'text/javascript; charset=UTF-8'        
        
        l = self.request.get('list')
        packageNames = l.split(',')
        
        scripts = []
        
        for package in packageNames:
            scripts.append(self.getPackage(package))
            
        self.response.out.write('\n'.join(scripts))
        
    def getPackage(self, name):    
        filepath = os.path.join(os.path.dirname(os.path.dirname(__file__)), 'js/'+name+'.js')
        return 'window.__onload_pkg__("'+name+'","'+open(filepath, 'r').read()+'");'


class GetScript(webapp.RequestHandler):
    def get(self):        
		
		self.response.headers['Content-Type'] = 'text/javascript; charset=UTF-8'
		
		mainpath = os.path.dirname(os.path.dirname(__file__))
		path = os.path.join(mainpath, 'js/main.xml')
		
		scriptsPath = open(path, 'r').readlines()
		
		response = []
		params = {}
		for script in scriptsPath:
			#response.append(template.render(os.path.join(mainpath, script.strip()), None))
			response.append('/**'+script+'**/');
			response.append(open(os.path.join(mainpath, script.strip()), 'r').read())
			
		self.response.out.write('\n\n\n'.join(response))

class GetApp(webapp.RequestHandler):
    def get(self):        
		
		self.response.headers['Content-Type'] = 'text/javascript; charset=UTF-8'
		
		mainpath = os.path.dirname(os.path.dirname(__file__))
		path = os.path.join(mainpath, 'js/main.xml')
		
		scriptsPath = open(path, 'r').readlines()
		
		response = []
		params = {}
		for script in scriptsPath:
			response.append('/**'+script+'**/');
			response.append(open(os.path.join(mainpath, script.strip()), 'r').read())
			
		self.response.out.write('\n\n\n'.join(response))
        

application = webapp.WSGIApplication([
    ('/dev/packages', GetPackages),
	('/dev/script', GetScript),
    ('/dev/app', GetApp),
    ],
    debug=True)     
            

def main():    
    run_wsgi_app(application)


if __name__ == '__main__':
    main()
